<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/5/16
 * Time: 9:59
 */

namespace app\service\order;

use app\company\model\CompanyGoodsRate;
use app\company\model\StoreOrderProfit;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class Profit extends Base
{

    /**
     * 订单分润计算 发生在订单完成时
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function update(): void
    {
        //每个商品的分润不一样
        $pay_type = $this->order->pay_type;
        $this->order->storeOrderDetails()->select()->each(function ($item) use ($pay_type) {
            $rate = CompanyGoodsRate::where('goods_id', $item->goods_id)->gs()->find();
            if (!$rate){
                Log::error('分润比例未设置'.$item->item_id);
                exception('分润比例未设置');
            }
            $profit = new StoreOrderProfit();
            $amount = $item->amount;
            //当是余额支付时有千分之6 的费率需要扣除 todo 配置项后期改
            if ($pay_type == 2)$amount = bcmul($amount, config('platform.wechat_profit'), 2);
            //分润 向下取2两位小数
            $profit->company_profit        = number_format($amount * $rate->company_rate / 100, 2);
            $profit->driver_profit         = number_format($amount * $rate->driver_rate / 100, 2);
            $profit->platform_profit       = number_format($amount * $rate->platform_rate / 100, 2);
            $profit->store_order_id        = $item->store_order_id;
            $profit->store_order_detail_id = $item->id;
            $profit->goods_id              = $item->goods_id;
            $profit->save();
        });
    }


}